import cv2 as cv
import sys
import os
from python_ai.common.xcommon import *
import matplotlib.pyplot as plt
import numpy as np
import time
import datetime


def my_show_img(img, title="no title", trans=None, **kwargs):
    global spn
    spn += 1
    plt.subplot(spr, spc, spn)
    if trans is not None:
        img = trans(img)
    plt.imshow(img, **kwargs)
    plt.axis('off')
    plt.title(title)


# img_dir = '../../../../../large_data/CV2/lesson/Day07'
# img_name = 'hammer.jpg'
# img_name = 'Moscow.jpeg'
# img_dir = '../../../../../large_data/pic'
# img_name = 'DSC05039.JPG'
# img_name = 'DSC05022_1.JPG'
# img_name = 'dog.jpg'
# img_name = 'dog_bird.jpg'
# img_name = 'football.jpg'
# img_name = 'messi5.jpg'
img_dir = '../../../../../large_data/pic/gray'
# img_name = '2008_0719_0019.JPG'
img_name = 'gray_in_pdf.png'
img_path = os.path.join(img_dir, img_name)

spr = 2
spc = 4
spn = 0
plt.figure(figsize=[12, 6])

sep('load')
img = cv.imread(img_path, cv.IMREAD_GRAYSCALE)
# img = cv.resize(img, None, fx=0.1, fy=0.1, interpolation=cv.INTER_CUBIC)
print('original shape', img.shape)
H, W = img.shape
H2 = H // 2
W2 = W // 2
my_show_img(img, 'original', cmap='gray')

# hist by cv of gray
sep('hist by cv of gray')
spn += 1
plt.subplot(spr, spc, spn)
hist = cv.calcHist([img], [0], None, [256], [0, 256])
print_numpy_ndarray_info(hist, 'hist')
plt.plot(hist, label='hist')
plt.title('hist by cv')

# cdf
cdf = hist.ravel().cumsum()
cdf_normalized = cdf * hist.max()
cdf_normalized /= cdf.max()
plt.plot(cdf_normalized, label='cdf', color='r')

spn += 1
plt.subplot(spr, spc, spn)
cdf_m = np.ma.masked_equal(cdf, 0)
plt.plot(cdf_m, label='after equal')
plt.legend()

spn += 1
plt.subplot(spr, spc, spn)
cdf_m = (cdf_m - cdf_m.min()) * 255 / (cdf_m.max() - cdf_m.min())
plt.plot(cdf_m, label='after norm')
cdf = np.ma.filled(cdf_m, 0)
cdf = cdf.astype('uint8')
plt.legend()

img2 = cdf[img]
my_show_img(img2, 'after', cmap='gray')

spn += 1
plt.subplot(spr, spc, spn)
hist = cv.calcHist([img2], [0], None, [256], [0, 256])
print_numpy_ndarray_info(hist, 'hist')
plt.plot(hist, label='hist')
plt.title('after')

# cdf
cdf = hist.ravel().cumsum()
cdf_normalized = cdf * hist.max()
cdf_normalized /= cdf.max()
plt.plot(cdf_normalized, label='cdf', color='r')
plt.legend()

# by lib
img3 = cv.equalizeHist(img)  # ATTENTION equalizeHist, API so easy, But only for gray pictures
my_show_img(img3, 'after by lib', cmap='gray')

plt.show()

img_all = np.concatenate((img, img2, img3), axis=1)
rate = 400 / W
img_all = cv.resize(img_all, None, fx=rate, fy=rate, interpolation=cv.INTER_CUBIC)
cv.imshow('before and after', img_all)
